package apollo

import (
	"fmt"

	"github.com/ZhengHe-MD/agollo/v4"

	"gitee.com/xfrm/middleware/xconfig"
)

type agolloObserver struct {
	observer *xconfig.ConfigObserver
}

func (o *agolloObserver) HandleChangeEvent(ce *agollo.ChangeEvent) {
	o.observer.HandleChangeEvent(transAgolloChangeEvent(ce))
}

func transAgolloChangeEvent(ace *agollo.ChangeEvent) *xconfig.ChangeEvent {
	var changes = map[string]*xconfig.Change{}
	for k, ac := range ace.Changes {
		if c, err := transAgolloChange(ac); err == nil {
			changes[k] = c
		}
	}
	return &xconfig.ChangeEvent{
		Source:    xconfig.Apollo,
		Namespace: ace.Namespace,
		Changes:   changes,
	}
}

func transAgolloChange(ac *agollo.Change) (change *xconfig.Change, err error) {
	ct, err := transAgolloChangeType(ac.ChangeType)
	if err != nil {
		fmt.Printf("transAgolloChange err:%s", err.Error())
		return
	}

	change = &xconfig.Change{
		OldValue:   ac.OldValue,
		NewValue:   ac.NewValue,
		ChangeType: ct,
	}
	return
}

func transAgolloChangeType(act agollo.ChangeType) (ct xconfig.ChangeType, err error) {
	switch act {
	case agollo.ADD:
		ct = xconfig.ADD
	case agollo.MODIFY:
		ct = xconfig.MODIFY
	case agollo.DELETE:
		ct = xconfig.DELETE
	default:
		err = fmt.Errorf("invalid apollo change type:%+v", act)
	}

	return
}
